package cn.edu.lzzy.vm;

import cn.edu.lzzy.entities.User;
import cn.edu.lzzy.utils.AuthUtils;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
import java.util.UUID;
import java.util.stream.Stream;


@Getter
@Setter
public class VmUser {
    private UUID id;
    private String nickName;//昵称
    private String userName;//账号
    private String email;//Email
    private String phone;//联系电话
    private String avatar;//头像
    private int type;//用户类型

    private String token;//随机
    private Date lastLogin;//最后一次登录的时间

    public VmUser() {
    }

    public VmUser(User user) {
        id=user.getId();
        nickName=user.getNickName();
        userName=user.getUserName();
        email=user.getEmail();
        phone=user.getPhone();
        avatar=user.getAvatar();
        type=user.getType();

        lastLogin=new Date();
        token=UUID.randomUUID().toString();

        AuthUtils.USERS.add(this);
    }
    public static VmUser apiLogin(User user){
        //vm为空对应用户注册的应用场景,否则对应用户登录应用成精
        VmUser vm = AuthUtils.USERS.stream()
                .filter(u ->u.userName.equals(user.getUserName()))
                .findFirst()
                .orElse(null);
        if(vm == null){
            vm=new VmUser(user);
        }else {
            //更新用户登录时间
            vm.lastLogin=new Date();
        }
        return vm;
    }
    public static VmUser create(User u,boolean admin){
        VmUser vm=new VmUser();
        vm.setId(u.getId());
        vm.setNickName(u.getNickName());

        vm.setUserName(u.getUserName());

        vm.setPhone(u.getPhone());
        vm.setEmail(u.getEmail());
        vm.setAvatar(u.getAvatar());

        vm.setToken("");
        if(admin){
            vm.setUserName(u.getUserName());
            vm.setType(u.getType());
        }else{
            vm.setUserName(u.getUserName());
            vm.setType(User.TYPE_STUDENT);
        }
        return vm;
    }
}
